
#include <stdlib.h>
#include "rscode.h"
#include "utility.h"
#include "libfec-ecc.h"

static void libfec_ecc_destroy(EccAdapter* ecc_adapter);
static int libfec_ecc_encode(EccAdapter* ecc_adapter, RSBlock* rs_block);

LibfecEcc* libfec_ecc_new()
{
	LibfecEcc* libfec_ecc;

	libfec_ecc = (LibfecEcc*)malloc(sizeof(LibfecEcc));
	if(NULL == libfec_ecc)
	{
		RES_NULL("Invoke malloc error.");
	}
	libfec_ecc->_parent.destroy = libfec_ecc_destroy;
	libfec_ecc->_parent.encode = libfec_ecc_encode;
	return libfec_ecc;
}

void libfec_ecc_destroy(EccAdapter* ecc_adapter)
{
	LibfecEcc* libfec_ecc;

	if(ecc_adapter != NULL)
	{
		libfec_ecc = (LibfecEcc*)ecc_adapter;
		free(libfec_ecc);
	}
}

int libfec_ecc_encode(EccAdapter* ecc_adapter, RSBlock* rs_block)
{
	int block_count1;
	int block_count2;
	int data_length1;
	int data_length2;
	int ecc_length;
	unsigned char* data_ptr, * ecc_ptr;
	RS* rs;
	int i;

	if(NULL == ecc_adapter || NULL == rs_block)
	{
		RES_INVAL("Argument is invalid.");
	}
	block_count1 = rs_block->_block_count1;
	block_count2 = rs_block->_block_count2;
	data_length1 = rs_block->_data_length1;
	data_length2 = rs_block->_data_length2;
	ecc_length = rs_block->_ecc_length;
	data_ptr = rs_block->_data;
	ecc_ptr = rs_block->_ecc;
	if(block_count1 <= 0 || block_count2 < 0 || data_length1 <= 0 || data_length2 < 0 || ecc_length <= 0 || NULL == data_ptr || NULL == ecc_ptr)
	{
		RES_INVAL("Argument is invalid.");
	}

	rs = init_rs(8, 0x11d, 0, 1, ecc_length, 255 - data_length1 - ecc_length);
	if(NULL == rs)
	{
		RES_INVAL("Invoke init_rs error.");
	}
	for(i = 0; i < block_count1; ++i)
	{
		encode_rs_char(rs, data_ptr, ecc_ptr);
		data_ptr += data_length1;
		ecc_ptr += ecc_length;
	}
	if(block_count2 > 0)
	{
		rs = init_rs(8, 0x11d, 0, 1, ecc_length, 255 - data_length2 - ecc_length);
		if(NULL == rs)
		{
			RES_INVAL("Invoke init_rs error.");
		}
		for(i = 0; i < block_count2; ++i)
		{
			encode_rs_char(rs, data_ptr, ecc_ptr);
			data_ptr += data_length2;
			ecc_ptr += ecc_length;
		}
	}
	return 0;
}

